package atom.core2.j2ee.util;

import java.io.File;
import java.io.ObjectInputStream;
import java.net.URLDecoder;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.servlet.ServletRequestContext;
import org.apache.log4j.Logger;

import atom.core0.util.FileUtil;


//MultipartStream s;
//DeferredFileOutputStream d;

public class ServletUtil
{
	private static String tempPath = "";// "d:\\temp\\buffer\\"; // 临时文件目录
	private static File tempPathFile;
	private static int BUFFER_SIZE = 4096;//
	private static int max_file_size = 40 * 1024 * 1024;// 4M

	private static Logger loginfo = Logger.getLogger(ServletUtil.class);
	private List<FileItem> formitems;
	private String charset;
	private static ServletContext servletContext=null;
	public static void setServletContext(ServletContext context)
	{
		servletContext = context;
	}
	public static ServletContext getServletContext()
	{
		return servletContext;
	}	
	public static void init(String path) throws ServletException
	{

		tempPath = System.getProperty("java.io.tmpdir");
		tempPathFile = new File(tempPath);
		if (!tempPathFile.exists())
		{
			tempPathFile.mkdirs();
		}
	}
	public static void mkdir(String uploadPath)
	{
		File uploadFile = new File(uploadPath);
		if (!uploadFile.exists())
		{
			uploadFile.mkdirs();
		}
		
	}
	public void analyseRequest(HttpServletRequest request) throws Exception
	{
		// boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		charset = request.getCharacterEncoding();
		boolean isMultipart = ServletFileUpload.isMultipartContent(new ServletRequestContext(request));
		if (isMultipart == true)
		{
			try
			{
				DiskFileItemFactory factory = new DiskFileItemFactory();
				factory.setSizeThreshold(BUFFER_SIZE); // 设置缓冲区大小，这里是4kb
				factory.setRepository(tempPathFile);// 设置缓冲区目录
				ServletFileUpload upload = new ServletFileUpload(factory);
				upload.setSizeMax(max_file_size); // 设置最大文件尺寸，这里是4MB
				
				formitems = upload.parseRequest(request);// 得到所有的文件
			}
			catch (Exception e)
			{
				loginfo.error(e.getMessage(), e);
				throw new Exception("analyseRequest分析表单错误:"+e.getMessage());
			}
		}
		else
		{
			throw new Exception("表单Form必须是multipart/form-data");
		}

	}

	public String saveFormFile(String formfilename, String dirPath,String filePrefix) throws Exception
	{
		if (formitems==null)
			throw new Exception("表单是空["+formfilename+"]");

		mkdir(dirPath);
		Iterator<FileItem> itr = formitems.iterator();
		while (itr.hasNext())
		{
			// 依次处理每个文件
			FileItem item = (FileItem) itr.next();
			String filefullName = item.getName();// 获得文件名，包括路径
			String filefieldname = item.getFieldName();

			if (filefieldname.equals(formfilename))
			{
				String fileName = FileUtil.getFileName(filefullName);
				if (!filePrefix.equals(""))
					fileName= filePrefix+"_"+fileName;
				File savedFile = new File(dirPath, fileName);
			/*	if (savedFile.exists())
					System.out.println("文件名重复"); */
				item.write(savedFile);
				
				return savedFile.getAbsolutePath();
			}
		}
		return "";
	}
	public String getFormItem(String formitemname) throws Exception
	{
		//item.getFieldName() 字段名 ;item.getName()文件名 包括路径;item.getString()文件内容或者字段内容
		if (formitems==null)
			throw new Exception("表单是空["+formitemname+"]");
		
		Iterator<FileItem> itr = formitems.iterator();
		while (itr.hasNext())
		{
			// 依次处理每个文件
			FileItem item = (FileItem) itr.next();
			String filefieldname = item.getFieldName();

			if (filefieldname.equals(formitemname))
			{
				String fileName = item.getName();// 获得文件名，包括路径
				if (fileName!=null)
					return fileName;
				else
				{
					//item.getString()是URLEncoder编码的，必须URLDecoder
					String value = URLDecoder.decode(item.getString(), charset) ;
					return value;
				}
			}
		}
		return "";
	}

	public static void saveFormFiles(HttpServletRequest request, String dirPath) throws Exception
	{
		// boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		boolean isMultipart = ServletFileUpload.isMultipartContent(new ServletRequestContext(request));
		if (isMultipart == true)
		{
			mkdir(dirPath);
			try
			{
				DiskFileItemFactory factory = new DiskFileItemFactory();
				factory.setSizeThreshold(BUFFER_SIZE); // 设置缓冲区大小，这里是4kb
				factory.setRepository(tempPathFile);// 设置缓冲区目录
				ServletFileUpload upload = new ServletFileUpload(factory);
				upload.setSizeMax(max_file_size); // 设置最大文件尺寸，这里是4MB

				List<FileItem> items = upload.parseRequest(request);// 得到所有的文件
				Iterator<FileItem> itr = items.iterator();
				while (itr.hasNext())
				{
					// 依次处理每个文件
					FileItem item = (FileItem) itr.next();

					String fileName = item.getName();// 获得文件名，包括路径
					if (fileName != null)
					{
						File fullFile = new File(item.getName());//为了获得文件名
						File savedFile = new File(dirPath, fullFile.getName());
						item.write(savedFile);
					}
				}
			}
			catch (Exception e)
			{
				e.printStackTrace();
			}
		}
		else
		{
			System.out.println("the enctype must be multipart/form-data");
		}

	}

	// fileName = "d:\\out.txt"
	// 只有enctype="multipart/form-data"的form才能读取流 普通form无法读取流
	// 测试使用，不抛出异常
	public static void saveRequestStreamToFile(HttpServletRequest request, String fileName)
	{
		try
		{
			java.io.InputStream is = request.getInputStream();
			FileUtil.saveStreamToFile(is,fileName);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	public static Object getObjectFromRequestStream(HttpServletRequest request) throws Exception
	{
		ObjectInputStream oi = null;

		oi = new ObjectInputStream(request.getInputStream());

		Object o = oi.readObject();
		return o;

	}

	public static int getMax_file_size()
	{
		return max_file_size;
	}

	public static void setMax_file_size(int max_file_size)
	{
		ServletUtil.max_file_size = max_file_size;
	}
	public static String getIpAddr(HttpServletRequest request)
	{
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
		{
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
		{
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
		{
			ip = request.getRemoteAddr();
		}
		if (ip != null)
			return ip.trim();
		else
			return "";

	}
}
